package com.xoa.service.knowledge.impl;

import com.xoa.dao.common.SysCodeMapper;
import com.xoa.dao.knowledge.KnowledgeColumnMapper;
import com.xoa.dao.knowledge.KnowledgeCustomerMapper;
import com.xoa.dao.knowledge.KnowledgeCustomerUselogMapper;
import com.xoa.dao.knowledge.KnowledgeDocfileMapper;
import com.xoa.dao.users.UserPrivMapper;
import com.xoa.dao.users.UsersMapper;
import com.xoa.model.common.SysCode;
import com.xoa.model.knowledge.KnowledgeColumn;
import com.xoa.model.knowledge.KnowledgeCustomer;
import com.xoa.model.knowledge.KnowledgeCustomerUselog;
import com.xoa.model.users.UserExt;
import com.xoa.model.users.UserPriv;
import com.xoa.model.users.Users;
import com.xoa.service.knowledge.ClientService;
import com.xoa.service.knowledge.KnowlidgeService;
import com.xoa.service.users.UsersService;
import com.xoa.util.LimsJson;
import com.xoa.util.ToJson;
import com.xoa.util.common.StringUtils;
import com.xoa.util.page.PageParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class ClientServiceImpl implements ClientService {

    @Autowired
    private KnowledgeCustomerMapper knowledgeCustomerMapper;

    @Autowired
    private SysCodeMapper sysCodeMapper;

    @Autowired
    private  KnowledgeColumnMapper knowledgeColumnMapper;

    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private UsersService usersService;

    @Autowired
    private UserPrivMapper userPrivMapper;

    @Autowired
    private KnowledgeCustomerUselogMapper knowledgeCustomerUselogMapper;

    @Override
    public ToJson getAllCustomer(KnowledgeCustomer customer,Integer page,Integer limit,String isSysCode) {
        ToJson json = new ToJson(1,"err");
        Map paramMap = new HashMap<>();
        PageParams pageParams = new PageParams();
        if(page!=null&&limit!=null){ //开启分页
            pageParams.setUseFlag(true);
            pageParams.setPage(page);
            pageParams.setPageSize(limit);
            paramMap.put("page", pageParams);
        }
        //栏目类别搜索
        if(customer.getColumnId()!=null && !StringUtils.checkNull(isSysCode)){
            String[] cId = customer.getColumnId().split(",");
            String[] isCode = isSysCode.split(",");
            String cIds="";
            String cType = "";
            for(int i = 0 ; i<cId.length ;i++  ){
                if(isCode[i].equals("true")){
                    cType += cId[i]+",";
                }else{
                    cIds += cId[i]+",";
                }
            }
            List<KnowledgeColumn> l =  knowledgeColumnMapper.selectByColumnTypes(cType.split(","));
            if(l.size()>0){
                for (KnowledgeColumn k:l) {
                    cIds += k.getColumnId()+",";
                }
            }
            //去重
            String[] split = cIds.split(",");
            Set set = new HashSet();
            for(int j = 0 ;j <split.length;j++){
                set.add(split[j]);
            }

            String[] objects = (String[]) set.toArray(new String[set.size()]);
            customer.setColumnIds(objects);
        }
        if(customer.getUserId()!=null && !"".equals(customer.getUserId())){
            List<Users> byName = usersMapper.getByName(customer.getUserId());
            if(byName!=null && byName.size()>0){
                String na = "";
                for (Users u :byName){
                    na += u.getUserId()+",";
                }
                if(na.length()>0){
                    customer.setCreateUserIds(na.split(","));
                }
            }

        }
        if(customer!=null){
            paramMap.put("customer",customer);
        }
        List<KnowledgeCustomer> customersList = knowledgeCustomerMapper.selectAllByParam(paramMap);
        for(KnowledgeCustomer customer1 : customersList){
            if(customer1.getCompanyNatrue()!=null){ //企业性质
                SysCode sysCode = sysCodeMapper.getSingleCode("KNOWLEDGE_COMPANY_NATRUE",customer1.getCompanyNatrue());
                if(sysCode!=null){
                    customer1.setCompanyNatrue(sysCode.getCodeName());
                }
            }
            if(customer1.getPrivType()!=null){ //权限类别
              if("0".equals(customer1.getPrivType())){
                  customer1.setPrivType("浏览");
              }else if("1".equals(customer1.getPrivType())){
                  customer1.setPrivType("下载");
              }
            }

            if(customer1.getContactUser()!=null){
                String userId = customer1.getContactUser();
                if(userId.endsWith(",")){
                    userId = userId.substring(0,userId.length()-1);
                }
                Users users = usersMapper.getUserId(userId);
                if(users!=null){
                    customer1.setContactUser(users.getUserName());
                }
            }
        }
        if(customersList!=null&&customersList.size()>0){
            json.setData(customersList);
            json.setFlag(0);
            if(page!=null&&limit!=null){ //开启分页
                json.setTotleNum(pageParams.getTotal());
            }
            json.setMsg("查询成功");
        }else {
            json.setFlag(0);
            json.setMsg("暂无数据");
        }
        return json;
    }

    @Override
    public ToJson addCustomer(HttpServletRequest request,KnowledgeCustomer customer, Users users) {
        ToJson json = new ToJson(1,"err");
        if(customer!=null&&users!=null){
            String userId = customer.getContactUser();
            if(userId.endsWith(",")){
                userId = userId.substring(0,userId.length()-1);
                customer.setContactUser(userId);
            }
            String columnIds = customer.getColumnId();
            if(!StringUtils.checkNull(columnIds)){
                String[] columnIdArr = columnIds.split(",");
                String cIds = ",";
                for(String cid : columnIdArr){
                    if(!StringUtils.checkNull(cid)){
                        cIds+=cid+",";
                    }
                }
                customer.setColumnId(cIds);
            }
            users.setUserPriv(0);
            ToJson addJson = usersService.addUser(users,new UserExt(),null,request);
            if(addJson!=null&&addJson.isFlag()){
                Users user = (Users)addJson.getObject();
                customer.setUserId(user.getUserId());
                int count = knowledgeCustomerMapper.insertSelective(customer);
                if(count>0){
                    json.setFlag(0);
                    json.setMsg("添加成功");
                }else {
                    json.setMsg("添加失败");
                }
            }else {
                json.setMsg("添加失败");
            }
        }else{
            json.setMsg("参数错误");
        }
        return json;
    }

    @Override
    public ToJson delCustomer(HttpServletRequest request,String ids) {
        ToJson json = new ToJson(1,"err");
        if(!StringUtils.checkNull(ids)){
            String[] idArr = ids.split(",");
            int count = 0;
            for(String id : idArr){
                if(!StringUtils.checkNull(id)){
                    KnowledgeCustomer kc = knowledgeCustomerMapper.selectByPrimaryKey(Integer.valueOf(id));
                    if(kc!=null){
                        Users user = usersMapper.seleById(kc.getUserId());
                        if(user!=null){
                            usersService.deleteUser(String.valueOf(user.getUid()),request);
                        }
                    }
                    count+=knowledgeCustomerMapper.deleteByPrimaryKey(Integer.valueOf(id));
                }
            }
            if(count>0){
                json.setFlag(0);
                json.setMsg("删除成功");
            }else {
                json.setMsg("删除失败");
            }
        }else{
            json.setMsg("参数错误");
        }
        return json;
    }

    @Override
    public ToJson getCustomerById(Integer customerId) {
        ToJson toJson = new ToJson(0,"err");
        if(customerId!=null){
            KnowledgeCustomer knowledgeCustomer = knowledgeCustomerMapper.selectByPrimaryKey(customerId);
            if(knowledgeCustomer != null){
                if(knowledgeCustomer.getColumnId()!=null){
                    String[] columnIdArr = knowledgeCustomer.getColumnId().split(",");
                    List<KnowledgeColumn> columnList = knowledgeColumnMapper.selectByColumnIds(columnIdArr);
                    if(columnList!=null&&columnList.size()>0){
                        String coluNames = "";
                        for(KnowledgeColumn know : columnList){
                            coluNames+=know.getColumnName()+",";
                        }
                        if(coluNames.endsWith(",")){
                            coluNames = coluNames.substring(0,coluNames.length()-1);
                        }
                        knowledgeCustomer.setColumnName(coluNames);
                    }
                }
                if(knowledgeCustomer.getContactUser()!=null){
                    Users user = usersMapper.getByUserId(knowledgeCustomer.getContactUser());
                    if(user!=null){
                        knowledgeCustomer.setContactUser(user.getUserName());
                    }
                }
                if(knowledgeCustomer.getUserId()!=null){
                    Users user = usersMapper.getByUserId(knowledgeCustomer.getUserId());
                    if(user!=null){
                        knowledgeCustomer.setByName(user.getByname());
                        knowledgeCustomer.setUserName(user.getUserName());
                        if(user.getUserPriv()!=null){
                            UserPriv userPriv = userPrivMapper.selectByPrimaryKey(user.getUserPriv());
                            if(userPriv!=null){
                                knowledgeCustomer.setUserPrivName(userPriv.getPrivName());
                            }
                            knowledgeCustomer.setUserPriv(user.getUserPriv());
                        }

                        knowledgeCustomer.setDeptId(user.getDeptId());
                        //knowledgeCustomer.setPassword(user.getPassword());
                    }
                }
                toJson.setObject(knowledgeCustomer);
                toJson.setMsg("查询成功");
                toJson.setFlag(1);
            }else{
                toJson.setMsg("没有数据");
            }
        }else {
            toJson.setMsg("参数错误");
        }
        return toJson;
    }

    @Override
    public ToJson editCustomer(HttpServletRequest request,KnowledgeCustomer customer,Users users) {
        ToJson json = new ToJson(1,"err");
        if(customer!=null&&customer.getCustomerId()!=null){
            Users u = usersMapper.seleById(users.getUserId());
            users.setUid(u.getUid());
            if(u!=null){
                ToJson editJson = usersService.editUser(request,users, new UserExt(), null);
                if(editJson.isFlag()){
                    int count = knowledgeCustomerMapper.updateByPrimaryKeySelective(customer);
                    if(count>0){
                        json.setFlag(0);
                        json.setMsg("编辑成功");
                    }else {
                        json.setMsg("编辑失败");
                    }
                }else {
                    json.setMsg("编辑失败");
                }
            }else{
                json.setMsg("用户不存在");
            }
        }else{
            json.setMsg("参数错误");
        }
        return json;
    }

    @Override
    public LimsJson getLogByUserId(HttpServletRequest request,String userId,Integer page,Integer limit){
        LimsJson limsJson = new LimsJson(1,"err");
        if(!StringUtils.checkNull(userId)){
            Map parme = new HashMap();
            PageParams pageParams = new PageParams();
            if(page!=null&&limit!=null){
                pageParams.setUseFlag(true);
                pageParams.setPage(page);
                pageParams.setPageSize(limit);
                parme.put("page", pageParams);
            }
            parme.put("userId",userId);
            List<KnowledgeCustomerUselog> logList = knowledgeCustomerUselogMapper.selectByUserId(parme);
            if(logList!=null&&logList.size()>0){
                for(KnowledgeCustomerUselog log : logList){
                    if(log.getUseType()!=null&&"0".equals(log.getUseType())){
                        log.setUseType("浏览");
                    }else if(log.getUseType()!=null&&"1".equals(log.getUseType())){
                        log.setUseType("下载");
                    }else{
                        log.setUseType("");
                    }
                    KnowledgeCustomer knowledgeCustomer = knowledgeCustomerMapper.selectByUserId(userId);
                    if(knowledgeCustomer!=null){
                        log.setCustomerName(knowledgeCustomer.getCompanyName());
                    }
                }
                if(page!=null&&limit!=null){
                    limsJson.setCount(pageParams.getTotal());
                }
                limsJson.setCode(0);
                limsJson.setData(logList);
            }else{
                limsJson.setMsg("暂无数据");
                limsJson.setCode(0);
            }
        }else{
            limsJson.setMsg("参数错误");
        }
        return limsJson;
    }
}
